
import { AdminUtils } from "@/models/adminModel";
import router from "@/router";
import axios, { AxiosError, AxiosResponse } from "axios";
import { ElLoading, ElMessage } from "element-plus";

const req = axios.create({
    baseURL: 'http://localhost:8080/manager',
    timeout: 5000
})

let loaing: any

// 请求前拦截
req.interceptors.request.use(
    (config: any) => {
        config.headers['token'] = AdminUtils.getAdmin().token

        if (config['data']) loaing = ElLoading.service({text: config.data.loading})
        else loaing = ElLoading.service({text: '请稍等'})

        return config;
    },
    (error: any) => {
        loaing?.close()
        ElMessage.error("请求失败")
        return Promise.reject(error);
    }
)

// 响应前拦截
req.interceptors.response.use(
    (response: AxiosResponse) => {
        loaing?.close()
        return response
    },
    (error: AxiosError) => {
        loaing?.close()
        if (error.code == "ERR_NETWORK") {
            ElMessage.error("服务器无响应")
        } 
        else if (error.status == 404) {
            ElMessage.error("404")
        }
        else if (error.status == 401) {
            ElMessage.error("请先登录")
            router.push("/login")
        }
        return Promise.reject(error);
    }
)

export default req